package com.shyroke.daydayzhuanweb.controller;

import com.shyroke.daydayzhuanapi.dto.*;
import com.shyroke.daydayzhuanapi.entity.NewsEntity;
import com.shyroke.daydayzhuanapi.entity.RoleEntity;
import com.shyroke.daydayzhuanapi.entity.SubmitArtEntity;
import com.shyroke.daydayzhuanapi.mapper.SubmitArtMapper;
import com.shyroke.daydayzhuandao.respository.NewsRepository;
import com.shyroke.daydayzhuandao.respository.SubmitArtRepository;
import com.shyroke.daydayzhuandao.respository.UserRepository;
import com.shyroke.daydayzhuansvc.service.IOSSService;
import com.shyroke.daydayzhuansvc.service.MailService;
import com.shyroke.daydayzhuansvc.service.SubmitArtService;
import com.shyroke.daydayzhuansvc.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author youhj
 * @date 2019/10/25 0025 下午 1:20/admin/submitArt
 */
@Controller
@RequestMapping(value = "/admin/submitArt")
public class SubmitArtController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IOSSService ossService;
    @Autowired
    private SubmitArtRepository submitArtRepository;
    @Autowired
    private SubmitArtMapper submitArtMapper;
    @Autowired
    private SubmitArtService submitArtService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private MailService mailService;
    @Autowired
    private NewsRepository newsRepository;

    @RequestMapping(value = "desc")
    public ModelAndView desc(ModelAndView model){

        model.setViewName("admin/submitArt/desc");
        return model;

    }

    @RequestMapping(value = "toAdd")
    public ModelAndView toAdd(ModelAndView model){

        model.setViewName("admin/submitArt/desc");
        return model;

    }

    @RequestMapping(value = "toPhoneAdd")
    public ModelAndView toPhoneAdd(ModelAndView model){

        model.setViewName("admin/submitArt/phoneAdd");
        return model;

    }
    /**
     * 保存商务合作内容的图片
     * @param file
     * @return
     */
    @RequestMapping(value = "uploadImg")
    @ResponseBody
    public LayEditRespon uploadImg(MultipartFile file){
        LayEditRespon respon = new LayEditRespon();

        if(file.isEmpty()){
            respon.setCode(-1);
            respon.setMsg("图片为空");
            return respon;
        }

        String fileName = file.getOriginalFilename();

        //获取上传图片的后缀，比如.png,.jpg
        String img_suff = fileName.substring(fileName.lastIndexOf("."),fileName.length());

        //获取随机产生的图片名字
        String saveFileName = RandomUtil.getRandomFileName()+img_suff;

        String path = OSSClientConstants.SubmitAtr_PATH+CommonUtil.getDateByFormat(new Date(),"yyyy-MM-dd")+"/"+saveFileName;
        String url;
        try {
            ossService.uploadImg(file,path);
            url = ossService.getImgUrl(path);
            //加水印
            url = url + OSSClientConstants.WATER_MARK;
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            respon.setCode(-1);
            respon.setMsg("图片上传失败");
            return respon;
        }

        Map<String,Object> data = new HashMap<String,Object>();

        data.put("src",url);

        respon.setCode(0);
        respon.setMsg("保存成功");
        respon.setData(data);

        return respon;
    }


    /**
     * 保存免费项目
     * @param project
     * @return
     */
    @PermissionAnnotation(permissionName = "submitArt:add")
    @RequestMapping(value = "save")
    @ResponseBody
    public R save(@RequestBody SubmitArt project, HttpSession session){
        UserMain user = (UserMain)session.getAttribute("user");
        if(user == null){
            return R.error("登录超时！请重新登录");
        }
        String content =  EmojiUtil.filterEmoji(project.getContent());
        project.setContent(content);
        SubmitArtEntity submitArtEntity = submitArtMapper.dtoToEntity(project,user.getId());
        submitArtRepository.save(submitArtEntity);
        return R.ok("保存成功！");
    }


    /**
     * 保存手机免费项目
     * @param project
     * @return
     */
    @PermissionAnnotation(permissionName = "submitArt:phoneadd")
    @RequestMapping(value = "phoneSave")
    @ResponseBody
    public R phoneSave(@RequestBody PhoneSubmitArt project, HttpSession session){
        this.handle(project);
        UserMain user = (UserMain)session.getAttribute("user");
        if(user == null){
            return R.error("登录超时！请重新登录");
        }
        project.setCreateId(user.getId());//创建人ID
        String content =  EmojiUtil.filterEmoji(project.getContent());
        project.setContent(content);
        SubmitArtEntity submitArtEntity = submitArtMapper.dtoToEntity(project,user.getId());
        submitArtRepository.save(submitArtEntity);

        //邮件提醒
        mailService.sendNewSubmitMail();
        //消息通知
        NewsEntity news = CommonUtil.createNews("有新的投稿文章，请及时处理！",1,"3");
        newsRepository.save(news);

        return R.ok("保存成功！");
    }

    private void handle(PhoneSubmitArt project) {

        if(!StringUtils.isEmpty(project.getStep1())){
            project.setStep1("<p>"+project.getStep1()+"</p>");
            if(!StringUtils.isEmpty(project.getStepImg1())){
                project.setStep1(project.getStep1()+"<p style=\"text-align: center;\"><img src="+project.getStepImg1()+"></img></p>");
            }
        }

        if(!StringUtils.isEmpty(project.getStep2())){
            project.setStep2("<p>"+project.getStep2()+"</p>");
            if(!StringUtils.isEmpty(project.getStepImg2())){
                project.setStep2(project.getStep2()+"<p style=\"text-align: center;\"><img src="+project.getStepImg2()+"></img></p>");
            }
        }

        if(!StringUtils.isEmpty(project.getStep3())){
            project.setStep3("<p>"+project.getStep3()+"</p>");
            if(!StringUtils.isEmpty(project.getStepImg3())){
                project.setStep3(project.getStep3()+"<p style=\"text-align: center;\"><img src="+project.getStepImg3()+"></img></p>");
            }
        }

        if(!StringUtils.isEmpty(project.getStep4())){
            project.setStep4("<p>"+project.getStep4()+"</p>");
            if(!StringUtils.isEmpty(project.getStepImg4())){
                project.setStep4(project.getStep4()+"<p style=\"text-align: center;\"><img src="+project.getStepImg4()+"></img></p>");
            }
        }

        if(!StringUtils.isEmpty(project.getStep5())){
            project.setStep5("<p>"+project.getStep5()+"</p>");
            if(!StringUtils.isEmpty(project.getStepImg5())){
                project.setStep5(project.getStep5()+"<p style=\"text-align: center;\"><img src="+project.getStepImg5()+"></img></p>");
            }
        }
        if(!StringUtils.isEmpty(project.getStep6())){
            project.setStep6("<p>"+project.getStep6()+"</p>");
            if(!StringUtils.isEmpty(project.getStepImg6())){
                project.setStep6(project.getStep6()+"<p style=\"text-align: center;\"><img src="+project.getStepImg6()+"></img></p>");
            }
        }

        if(!StringUtils.isEmpty(project.getStep7())){
            project.setStep7("<p>"+project.getStep7()+"</p>");
            if(!StringUtils.isEmpty(project.getStepImg7())){
                project.setStep7(project.getStep7()+"<p style=\"text-align: center;\"><img src="+project.getStepImg7()+"></img></p>");
            }
        }

        String contentStep = "";
        contentStep = contentStep+  "<p>"+project.getSummary()+"</p>";
        if(!StringUtils.isEmpty(project.getStep1())){
            contentStep += project.getStep1();
        }
        if(!StringUtils.isEmpty(project.getStep2())){
            contentStep += project.getStep2();
        }
        if(!StringUtils.isEmpty(project.getStep3())){
            contentStep += project.getStep3();
        }
        if(!StringUtils.isEmpty(project.getStep4())){
            contentStep += project.getStep4();
        }
        if(!StringUtils.isEmpty(project.getStep5())){
            contentStep += project.getStep5();
        }
        if(!StringUtils.isEmpty(project.getStep6())){
            contentStep += project.getStep6();
        }
        if(!StringUtils.isEmpty(project.getStep7())){
            contentStep += project.getStep7();
        }

        String wrap = "<div class=\"article-content\">";
        String wrapEnd = "</div>";

        project.setContent(wrap+contentStep+wrapEnd);
    }


    /**
     * 跳转到投稿管理的页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "list")
    public ModelAndView list(ModelAndView model) {

        model.setViewName("admin/submitArt/list");

        return model;
    }

    /**
     * 加载免费项目的数据
     *
     * @return
     */
    @RequestMapping(value = "getProjectList")
    @ResponseBody
    public TabelData<SubmitArtDto> getProjectList(Page page, SubmitArt submitArt, HttpSession session) {
        UserMain user = (UserMain)session.getAttribute("user");
        submitArt.setUserId(user.getId());
        return  submitArtService.getProjectList(page,submitArt);
    }

    @RequestMapping(value = "descAndEdit/{id}")
    public ModelAndView descAndEdit(@PathVariable("id")Integer id, ModelAndView model){
        Optional<SubmitArtEntity> optionalSubmitArtEntity = submitArtRepository.findById(id);
        if (optionalSubmitArtEntity.isPresent()) {
            SubmitArtEntity submitArtEntity = optionalSubmitArtEntity.get();
            model.addObject("submitArt",submitArtEntity);
        }
        model.setViewName("admin/submitArt/artEdit");
        return model;
    }

    /**
     * 修改项目
     * @param art
     * @return
     */
    @PermissionAnnotation(permissionName = "submitArt:update")
    @RequestMapping(value = "update")
    @ResponseBody
    public R update(@RequestBody SubmitArt art){
        Optional<SubmitArtEntity> optionalSubmitArtEntity = submitArtRepository.findById(art.getId());
        if (!optionalSubmitArtEntity.isPresent()) {
            return R.error("没有找到id对应的实体");
        }
        SubmitArtEntity submitArtEntity = optionalSubmitArtEntity.get();
        if(submitArtEntity.getIsCheck() == 1){
            return R.error("审核通过不能修改！");
        }
        submitArtEntity.setUpdateTime(new Date());
        submitArtEntity.setIsCheck(0);
        submitArtEntity.setMemo(null);
        submitArtEntity.setKeyword(art.getKeyword());
        submitArtEntity.setTitle(art.getTitle());
        submitArtEntity.setSummary(art.getSummary());
        submitArtEntity.setContent(art.getContent());
        submitArtRepository.save(submitArtEntity);
        return R.ok("修改成功！");
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @PermissionAnnotation(permissionName = "submitArt:delete")
    @RequestMapping(value = "delete")
    @ResponseBody
    public R delete(Integer id,HttpSession session){
        UserMain user = (UserMain)session.getAttribute("user");
        Optional<SubmitArtEntity> optionalSubmitArtEntity = submitArtRepository.findById(id);
        if (!optionalSubmitArtEntity.isPresent()) {
            return R.error("没有找到id对应的实体");
        }
        SubmitArtEntity submitArtEntity = optionalSubmitArtEntity.get();
        boolean isAdmin = false;
        Set<RoleEntity> roleList = userRepository.findByName(user.getName()).getRoleList();
        if(!CollectionUtils.isEmpty(roleList)){
            for(RoleEntity role:roleList){
                if(role.getId() == 1){
                    isAdmin = true;
                }
            }
        }
        if(!isAdmin){
            if(!submitArtEntity.getCreateId().equals(user.getId())){
                return R.error("拥有者错误!");
            }
        }
        submitArtRepository.deleteById(submitArtEntity.getId());
        return R.ok("删除成功！");
    }

}
